package com.neusoft.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.neusoft.util.VerificationCode;
import com.neusoft.mapper.VerificationMapper;
import com.neusoft.service.VerificationService;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;

import static com.aliyun.teautil.Common.toJSONString;
@Service
public class VerificationServiceImpl implements VerificationService{
	@Autowired
	private VerificationCode verificationCode;
	
	@Autowired
	private VerificationMapper verificationMapper;
	
	@Override
    public int sendVerificationCodeById(String userId) throws Exception{
         String code = verificationCode.generateVerificationCode();
    	 String regex = "^1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$";
         if(!userId.matches(regex)) return -1;
         // 创建阿里云短信客户端
    	 com.aliyun.dysmsapi20170525.Client client = verificationCode.createClient();
    	 // 创建短信请求对象
    	 com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(userId)
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setTemplateParam("{\"code\":\"" + code + "\"}");
    	
    	try {
            // 复制代码运行请自行打印 API 的返回值
    		verificationMapper.saveVerificationCode(userId, code);
            client.sendSmsWithOptions(sendSmsRequest, new com.aliyun.teautil.models.RuntimeOptions()); // 发送短信
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // 创建一个定时任务线程池
            scheduler.schedule(() -> { // 提交一个延迟任务，在 1分钟后自动执行删除操作
                verificationMapper.deleteVerificationCode(userId,code);
            }, 1, TimeUnit.MINUTES);
            return 1;
        } catch (TeaException error) { // 捕获阿里云特有异常
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            return 0;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            com.aliyun.teautil.Common.assertAsString(error.message);
            return 0;
        }
    }
	public int judgeVerificationCodeById(String userId,String code) {
		String truecode = verificationMapper.getVerificationCodeById(userId);
		if(truecode==null) return -1;
		else if(truecode.equals(code)) return 1;
		else return 0;
	}
}
